package io.kubesphere.devops.core;

import com.google.common.eventbus.EventBus;
import io.kubesphere.devops.core.executor.SQLUndoLog;
import io.kubesphere.devops.service.MergeCommitEvent;
import io.kubesphere.devops.service.MergeEvent;
import io.kubesphere.devops.service.MergeRevertEvent;
import io.kubesphere.devops.service.SimpleLogListener;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;

public class ConnectionProxy implements Connection {
    private DataSourceProxy dataSourceProxy;
    private Connection targetConnection;
    private ConnectionContext context = new ConnectionContext();
    final EventBus eventBus = new EventBus();
    private final static LockRetryPolicy LOCK_RETRY_POLICY = new LockRetryPolicy();

    public ConnectionProxy(DataSourceProxy dataSourceProxy, Connection targetConnection) {
        this.dataSourceProxy = dataSourceProxy;
        this.targetConnection = targetConnection;
    }

    /**
     * Gets context.
     *
     * @return the context
     */
    public void appendUndoItem(SQLUndoLog sqlUndoLog) {
        context.appendUndoItem(sqlUndoLog);
    }

    /**
     * Gets db type.
     *
     * @return the db type
     */
    public String getDbType() {
        return dataSourceProxy.getDbType();
    }

    @Override
    public Statement createStatement() throws SQLException {
        return this.targetConnection.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return targetConnection.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return targetConnection.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        this.targetConnection.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return this.targetConnection.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        try {
            LOCK_RETRY_POLICY.execute(() -> {
                doCommit();
                return null;
            });
        } catch (SQLException e) {
            if (targetConnection != null && !getAutoCommit() && !getContext().isAutoCommitChanged()) {
                rollback();
            }
            throw e;
        } catch (Exception e) {
            throw new SQLException(e);
        }

        this.targetConnection.setAutoCommit(false);
        this.targetConnection.commit();

    }

    public ConnectionContext getContext() {
        return this.context;
    }

    private void doCommit() throws SQLException {
        this.targetConnection.setAutoCommit(false);
        if (context.inGlobalTransaction()) {
            processGlobalTransactionCommit();
        } else {
            targetConnection.commit();
        }
    }

    private void branchBind(SimpleLogListener listener) {
        String branchId = UuidUtils.getRandomUUIDString();
        context.setBranchId(branchId);
        eventBus.register(listener);
        MergeEvent branchBegin = new MergeEvent(context.getXid(), context.getBranchId());
        branchBegin.setPartitionName(this.dataSourceProxy.getPartitionName());
        eventBus.post(branchBegin);
    }

    private void branchSuccess(SimpleLogListener listener) {
        // 发布成功事件,更新merging log  detail
        MergeCommitEvent branchSuccessEvent = new MergeCommitEvent(context.getXid(), context.getBranchId());
        //向订阅者发送消息
        eventBus.post(branchSuccessEvent);
        eventBus.unregister(listener);
    }

    private void branchFail(SimpleLogListener listener) {
        // 发布失败事件,更新merging log  detail
        MergeRevertEvent branchFailEvent = new MergeRevertEvent(context.getXid(), context.getBranchId());
        //向订阅者发送消息
        eventBus.post(branchFailEvent);
        eventBus.unregister(listener);
    }

    private void processGlobalTransactionCommit() throws SQLException {
        //获取分支记录日志
        SimpleLogListener listener = ListenerHolder.getInstance().getSimpleLogListener();
        try {
            branchBind(listener);
            UndoLogManagerFactory.getUndoLogManager(this.getDbType()).flushUndoLogs(this);
            targetConnection.commit();
            //发布成功提交事件
            branchSuccess(listener);
        } catch (Throwable ex) {
            //提价出现任何异常发布分支异常事件
            branchFail(listener);
            targetConnection.rollback();
            throw ex;
        }
        //清空变量
        context.reset();
    }

    @Override
    public void rollback() throws SQLException {
        targetConnection.rollback();
        context.reset();
    }

    @Override
    public void close() throws SQLException {
        this.targetConnection.close();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return this.targetConnection.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return this.targetConnection.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        this.targetConnection.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return this.targetConnection.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        this.targetConnection.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return this.targetConnection.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        this.targetConnection.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return this.targetConnection.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return this.targetConnection.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        this.targetConnection.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return targetConnection.createStatement(resultSetType,resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, resultSetType,
                resultSetConcurrency);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return targetConnection.prepareCall(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return targetConnection.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        targetConnection.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        targetConnection.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return targetConnection.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return targetConnection.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return targetConnection.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {

        targetConnection.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        targetConnection.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return targetConnection.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, resultSetType,
                resultSetConcurrency, resultSetHoldability);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return targetConnection.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, autoGeneratedKeys);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, columnIndexes);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, columnNames);
        return new PreparedStatementProxy(this, preparedStatement, sql);
    }

    @Override
    public Clob createClob() throws SQLException {
        return targetConnection.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return targetConnection.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return targetConnection.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return targetConnection.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return targetConnection.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        targetConnection.setClientInfo(name, value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        targetConnection.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return targetConnection.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return targetConnection.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return targetConnection.createArrayOf(typeName, elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return targetConnection.createStruct(typeName, attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {

        targetConnection.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return targetConnection.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        targetConnection.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        targetConnection.setNetworkTimeout(executor, milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return targetConnection.getNetworkTimeout();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return targetConnection.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return targetConnection.isWrapperFor(iface);
    }

    public DataSourceProxy getDataSourceProxy() {
        return this.dataSourceProxy;
    }

    public Connection getTargetConnection() {

        return this.targetConnection;
    }

    public void bind(String xid) {
        context.bind(xid);
    }

    public static class LockRetryPolicy {
        public <T> T execute(Callable<T> callable) throws Exception {
            return callable.call();
        }
    }

}
